<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 *  学生门禁闸机相关接口
 */

class Gate extends BaseController {

	public function __construct() {
        parent::__construct();
    }


    // 用户ID前缀
    private $teacherPrefix = "t";
    private $studentPrefix = "s";

    // 获取闸机任务
    public function get_gate_task(){
        $this->load->model("GateModel");

        // 获取闸机信息
        $deviceSn = $this->get("sn");
        $gateInfo = $this->GateModel->get_gate_info($deviceSn);
        if(!$gateInfo) throw new Exception("设备序列号不存在");

        // 获取闸机任务
        $params['pageStart'] = 0;
        $params['pageSize']= 200;
        $params['gateId'] = $gateInfo['id'];
        $params['taskState'] = GATE_TASK_STATE_NEW;
        $params['isDelete'] = 0;
        $mTaskList = $this->GateModel->get_gate_task($params);
        // 返回值
        $ret = array();
        foreach($mTaskList as $task) {
            // 用户ID前缀，区分教师和学生
            $idPrefix = "";
            if($task['user_type'] == GATE_USER_TYPE_TEACHER) $idPrefix = $this->teacherPrefix;
            else if($task['user_type'] == GATE_USER_TYPE_STUDENT) $idPrefix = $this->studentPrefix;

            $taskContent = array();
            switch($task['task_type']) {
                case GATE_TASK_TYPE_ADD:
                case GATE_TASK_TYPE_UPDATE:
                    $taskContent['version'] = "0.9";
                    $taskContent['cmd'] = $task['task_type'] == GATE_TASK_TYPE_ADD ? "add person jpg" : "update person jpg";
                    $taskContent['id'] = $idPrefix. $task['user_id'];
                    $taskContent['name'] = $task['user_name'];
                    $taskContent["role"] = 1;
                    $taskContent['customer_text'] = $task['user_type'];
                    $taskContent["image_num"] = 1;
                    $taskContent["reg_images"] = array(
                        array(
                            "format" => "jpg", 
                            "image_data" => $task['user_face_image']. "!/rotate/360"
                        )
                    );
                    $taskContent["wg_card_id"] = $task['user_id'];
                    $taskContent["term"] = "forever";
                    $taskContent["term_start"] = "useless";
                    break;
                case GATE_TASK_TYPE_DELETE:
                    $taskContent['version'] = "0.9";
                    $taskContent['cmd'] = "delete person(s)";
                    $taskContent['flag'] = -1;
                    $taskContent['id'] = $idPrefix. $task['user_id'];
                    break;
            }
            $ret[] = $taskContent;
        }
        exit(json("", true, $ret));
    }

    // 闸机任务回调
    public function gate_task_callback(){
        $this->load->model("GateModel");
        // 获取设备编码
        $deviceSn = $this->get("sn");
        $gateInfo = $this->GateModel->get_gate_info($deviceSn);
        if(!$gateInfo) throw new Exception("设备序列号不存在");
        // 获取任务类型
        $taskType = urldecode($this->get("type"));
        switch ($taskType) {
            case "add person jpg":
                $taskType = GATE_TASK_TYPE_ADD;
                break;
            case "update person jpg":
                $taskType = GATE_TASK_TYPE_UPDATE;
                break;
            case "delete person(s)":
                $taskType = GATE_TASK_TYPE_DELETE;
                break;
        }
        // 获取用户ID
        $userId = $this->get("user");
        // 获取用户ID前缀
        $idPrefix = substr($userId, 0, 1);
        // 用户类型
        $userType = "";
        if($idPrefix == $this->teacherPrefix) {
            $userType = GATE_USER_TYPE_TEACHER;
            $userId = str_replace($this->teacherPrefix, "", $userId);
        }
        else if($idPrefix == $this->studentPrefix) {
            $userType = GATE_USER_TYPE_STUDENT;
            $userId = str_replace($this->studentPrefix, "", $userId);
        }

        // 回调结果
        $code = $this->get("code");

        $taskStateNew = GATE_TASK_STATE_NEW;
        // 解决第一次新增时失败，第二次任务类型为修改的问题
        if($code == 22 && $taskType == GATE_TASK_TYPE_UPDATE) {
            // 该用户所有未处理的修改类型任务，任务类型设置为新增
            $taskTypeUpdate = GATE_TASK_TYPE_UPDATE;
            $this->db->update(GateModel::$gateTaskTable, array('task_type' => GATE_TASK_TYPE_ADD), "`device_sn` = '{$deviceSn}' AND `user_id` = '{$userId}' AND `task_type` = '{$taskTypeUpdate}' AND `task_state` = '{$taskStateNew}' AND `user_type` = '{$userType}'");
        } else {
            // 更新任务状态
            $update['task_state'] = $code == 0 ? GATE_TASK_STATE_OK : GATE_TASK_STATE_FAIL;
            $update['task_state_desc'] = $code;
            $update['updatetime'] = date("Y-m-d H:i:s");
            $this->db->update(GateModel::$gateTaskTable, $update,"`device_sn` = '{$deviceSn}' AND `user_id` = '{$userId}' AND `task_type` = '{$taskType}' AND `task_state` = '{$taskStateNew}' AND `user_type` = '{$userType}'");
        }
    }

    // 学生签到接口
    public function student_sign(){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取学生信息
        $studentId = $this->post('userId');
        if(empty($studentId)) {
            throw new Exception('参数错误');
        }

        // 检查ID，如果是老师则不考勤
        $idPrefix = substr($studentId, 0, 1);
        if($idPrefix == $this->teacherPrefix) return;
        else {
            if($idPrefix == $this->studentPrefix) {
                $studentId = str_replace($this->studentPrefix, "", $studentId);
            }
        }
        


        // 获取学生信息
        $studentInfo = $this->schoolModel->get_student_info($studentId);
        if(!$studentInfo || $studentInfo['is_delete'] == 1 || $studentInfo['is_graduated'] == 1) throw new Exception("签到失败，找不到对应的学生");
        // 签到图片，base64
        $imageBase64 = $this->post("image", false);
        if(empty($imageBase64)) {
            throw new Exception('图片参数错误');
        }
        // 判断base64字符串是否有带前缀data:image/jpg;base64,
        if(strstr($imageBase64, 'data:image/') == false) {
            // 添加前缀
            $imageBase64 = 'data:image/jpg;base64,' . $imageBase64;
        }

        // 设备序列号
        $deviceSn = $this->post('deviceSn');
        if(empty($deviceSn)) {
            throw new Exception('参数错误');
        }
        // 获取设备信息
        $gateInfo = $this->schoolModel->get_gate_info_device_sn($studentInfo['school_id'], $deviceSn);
        if(empty($gateInfo)) {
            throw new Exception('设备序列号不存在');
        }

        // 签到状态为闸机入口还是出口考勤
        if($gateInfo['device_is_exit'] == 1) {
            $state = SIGN_STATE_GATE_EXIT;
        } else {
            $state = SIGN_STATE_GATE_ENTRY;
        }

        // 签到时间
        $signTime = date('Y-m-d H:i:s');
        // 判断10分钟内是否有重复提交，如设备出入口不同，可重复提交
        $signInfo = $this->classesModel->get_sign_info_by_createtime_gate(date("Y-m-d H:i:s", strtotime($signTime)), $studentInfo['id']);
        if($gateInfo['device_is_exit'] == 1) {
            if($signInfo['state'] == SIGN_STATE_GATE_EXIT) {
                throw new Exception('10分钟内不需要重复签到');
            }
        }
        if($gateInfo['device_is_exit'] == 0) {
            if($signInfo['state'] == SIGN_STATE_GATE_ENTRY) {
                throw new Exception('10分钟内不需要重复签到');
            }
        }
        // if($signInfo && $signInfo['device_sn']) {
        //     $signGateInfo = $this->schoolModel->get_gate_info_device_sn($studentInfo['school_id'], $signInfo['device_sn']);
        //     if($gateInfo['device_is_exit'] == 1) {

        //     }
        //     if($signGateInfo['device_is_exit'] == $gateInfo['device_is_exit']) {
        //         // // 测试服不限制
        //         // if(ENV != 'test' && ENV != 'local') {
        //             throw new Exception('10分钟内不需要重复签到');
        //         // }
        //     }
        // }

        // base64
        // 写入图片
        require_once('vendor/autoload.php');
        $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".jpg";
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $client = new Upyun\Upyun($serviceConfig);
        $signImg = UP_URL. $fileName;
        try{
            $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
        } catch(Exception $e) {
            // 捕获同个图片名，上传多次报错
            // $signImg = $e->getMessage();
            throw new Exception("429 Too Many Requests");
        }
        // 写文件上传调试日志
        if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");

        $classInfo = $this->classesModel->get_class_info($studentInfo['class_id']);
        $brandInfo = $this->classesModel->get_brand_info_by_class($studentInfo['class_id']);

        // 如果是同步学校，设置sign_is_submit=1
        $schoolInfo = $this->schoolModel->get_school_info($studentInfo['school_id']);
        if($schoolInfo['school_from'] == X_DATA_HAOZHUANYE) {
            $insert['sign_is_submit'] = 1;
        } else {
            $insert['sign_is_submit'] = 0;
        }

        // 入库，做个毛线逻辑
        $insert['school_id'] = $studentInfo['school_id'];
        $insert['class_id'] = $studentInfo['class_id'];
        $insert['course_id'] = 0;
        $insert['student_id'] = $studentInfo['id'];
        $insert['student_card_number'] = $studentInfo['realcard'];
        $insert['brand_id'] = $brandInfo ? $brandInfo['id'] : 0;
        $insert['sign_type'] = SIGN_TYPE_GATE;
        $insert['state'] = $state;
        $insert['sign_img'] = $signImg;
        $insert['sign_date'] = date("Y-m-d", strtotime($signTime));
        $insert['temperature'] = '';
        $insert['createtime'] = date("Y-m-d H:i:s", strtotime($signTime));
        $insert['device_sn'] = $deviceSn;
        $this->db->insert(ClassesModel::$signTable, $insert);

        // 返回值
        $ret['name'] = $studentInfo['realname'];
        $ret['signId'] = $this->db->insert_id();

        // 插入考勤临时表
        $this->db->insert(ClassesModel::$signTempTable, $insert);

        // 发送模板消息
        $url = wx_url('pub/student_sign_detail/' . $ret['signId']);
        $data = array(
            'first' => array(
                'value' => '家长您好，' . $studentInfo['realname'] . '同学已经成功签到'
            ),
            'keyword1' => array(
                'value' => $classInfo['class_name']
            ),
            'keyword2' => array(
                'value' => date("Y-m-d H:i:s", strtotime($signTime))
            ),
            'keyword3' => array(
                'value' => $studentInfo['realname']
            )
        );
        $this->load->library('wxtemplate');
        $this->wxtemplate->send_template_msg_for_user($studentInfo['id'], BIND_TYPE_STUDENT, WX_TEMPLATE_SCHEDULE, $data, $url);

        exit(json("", true, $ret));
    }
}
